import Taro from "@tarojs/taro"
import config from "../config/index"
import { HTTP_STATUS } from "../../constants/status"
import { logError } from "../../utils/error"

export default {

  baseOptions(params, method = 'GET') {
    let { url, data } = params;
    let contentType: string = 'application/json;charset=UTF-8'
    contentType = params.contentType || contentType;
    type OptionType = {
      url: string,
      data?: object | string,
      method?: any,
      header: object,
      // cors_mode: string,
      success: any,
      error: any,
    }
    const option: OptionType = {
      url: `${config.domain}${url}`,
      data: data,
      method: method,
      header: {
        "Accept": "application/json",
        "Content-Type": contentType
      },
      // cors_mode: "cors",
      success(res: any) {
        console.log('res', res)
        if (res.statusCode === HTTP_STATUS.NOT_FOUND) {
          return logError('api', '请求资源不存在')
        } else if (res.statusCode === HTTP_STATUS.BAD_GATEWAY) {
          return logError('api', '服务端出现了问题')
        } else if (res.statusCode === HTTP_STATUS.FORBIDDEN) {
          return logError('api', '没有权限访问')
        } else if (res.statusCode === HTTP_STATUS.AUTHENTICATE) {
          Taro.clearStorage()
          Taro.navigateTo({
            url: '/pages/login/index'
          })
          return logError('api', '请先登录')
        } else if (res.statusCode === HTTP_STATUS.SUCCESS) {
          return res.data
        }
      },
      error(e) {
        console.log(e);
      }
    }
    if (Taro.getStorageSync('TOKEN')) {
      option.header['token'] = Taro.getStorageSync('TOKEN')
    }
    return Taro.request(option)
  },
  get(url: string, data?: object) {
    let option = { url, data }
    return this.baseOptions(option)
  },
  post: function (url: string, data?: object, contentType?: string) {
    let params = { url, data, contentType }
    return this.baseOptions(params, 'POST')
  },
  put(url: string, data?: object) {
    let option = { url, data }
    return this.baseOptions(option, 'PUT')
  },
  delete(url: string, data?: object) {
    let option = { url, data }
    return this.baseOptions(option, 'DELETE')
  }
}